package logic

import (
	"context"
	"errors"
	"userrpc/models/mysql"
	"userrpc/models/redis"
	"userrpc/pkg"

	"userrpc/internal/svc"
	"userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("sendSmslogin" + in.Tel)
	if get.Val() == "" {
		return nil, errors.New("暂未获取短信验证码")
	}
	if get.Val() != in.SendSmsCode {
		return nil, errors.New("短信验证码输入错误")
	}

	var user mysql.User
	login, err := user.Login(in.Tel)
	if err != nil {
		return nil, errors.New("登录失败")
	}
	users := mysql.User{
		Tel:      in.Tel,
		Password: pkg.Md5(in.Tel),
		NickName: in.Tel,
	}
	if login.ID == 0 {
		err = users.Register()
		if err != nil {
			return nil, errors.New("自动注册失败")
		}
	}

	redis.Rdb.Del("sendSmslogin" + in.Tel)

	return &userrpc.UserLoginResponse{}, nil
}
